//
//  CUserManager.swift
//  JTYP
//
//  Created by Groot on 2017/12/5.
//  Copyright © 2017年 inspur. All rights reserved.
//

import Alamofire

class CUserManager {
    
    // 单例
    static let shareInstance = CUserManager()
    // 存储
    private let defaults = Defaults()
    // user key
    private static let KUserKey = Key<CUser>("KUserKey")
    // notification name
    static let KUserStatusChanged = "KUserStatusChanged"
    
    var cUser: CUser?

    private init() {
        cUser = getUser()
    }
    
    private func userInfoChanged() {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: CUserManager.KUserStatusChanged), object: nil)
    }
    
    func getToken(account: String, pwd: String, block: @escaping (_ responseObject:CUser?, _ message:String?) -> Void) {
        let param = ["account": account,
                     "password": pwd,
                     "deviceid": UIDevice.current.identifierForVendor?.uuidString ?? ""]
        
        NetWorkUtil.shareInstance.postForObject(objectType: ObjResponse<CUser>.self, urlString: Server.login, parameters: param, finishCallBack: { (response, err) in
            guard let result = response else {
                block(nil, err?.localizedDescription)
                return
            }
            guard  result.code == ECode.success.rawValue, let u = result.data else{
                block(nil, result.message)
                return
            }
            self.save(user: u)
            block(u, nil)
        }, tokenNeeded: false)
        
    }
    
    func refreshToken(block: @escaping (_ success: Bool) -> Void) {
        guard let u = getUser(), !(u.refreshToken?.isEmpty ?? true) else {
            block(false)
            return
        }
        let param = ["token": u.refreshToken ?? ""]

        NetWorkUtil.shareInstance.postForObject(objectType: ObjResponse<CUser>.self, urlString: Server.refreshToken, parameters: param, finishCallBack: {[unowned self] (response, err) in
            guard let result = response, result.code == ECode.success.rawValue else {
                self.logout()
                block(false)
                return
            }
            guard let accessToken = result.data?.accessToken, !accessToken.isEmpty else {
                block(false)
                return
            }
            result.data?.refreshToken = u.refreshToken
            self.save(user: result.data)
            block(true)
        }, tokenNeeded: false)
    }
    

    
    private func save(user: CUser?) {
        guard let u = user else {
            return
        }
        self.cUser = user
        
        defaults.set(u, for: CUserManager.KUserKey)
        
        userInfoChanged()
    }
    
    private func clearUserInfo() {
        defaults.clear(CUserManager.KUserKey)
        cUser = nil
    }
    
    func logout() {
        // 清除登录用户信息
        clearUserInfo()
        // 通知 用户已注销
        userInfoChanged()
        // 切换到登录页
        (UIApplication.shared.delegate as? AppDelegate)?.changeStoryboard()
    }
    
    private func getUser() -> CUser?{
        guard let u = defaults.get(for: CUserManager.KUserKey) else{
            return nil
        }
        return u
    }
    
}
